<template>
  <div>
    <div class="ele-page-header">
      <div class="ele-page-title">主平台系统配置</div>
    </div>
    <div class="ele-body"
         style="padding-bottom: 71px">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="130px"
               @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="12"
                  :md="12">
            <el-card shadow="never"
                     header="案例中心配置"
                     body-style="padding: 22px 22px 0 22px;">
              <el-row :gutter="15">
                <el-col :lg="24"
                        :md="24">
                  <!-- <el-form-item label="appid:"
								  prop="xcxAppid">
					  <el-input v-model="form.xcxAppid"
								placeholder="请输入小程序appid"
								clearable></el-input>
					</el-form-item>
					<el-form-item label="appSecret:"
								  prop="loginBackground">
					  <el-input v-model="form.xcxAppsecret"
								show-password
								placeholder="请输入小程序appSecret"
								clearable></el-input>
					</el-form-item> -->

                  <el-form-item label="标题分类:"
                                prop="clockTime">
                    <el-tag :key="tag"
                            v-for="tag in dynamicTagsCase"
                            closable
                            :disable-transitions="false"
                            @close="handleCloseTagCase(tag,'caseLabel')">
                      {{ tag }}
                    </el-tag>
                    <el-input class="input-new-tag"
                              v-if="inputVisibleCase"
                              v-model="inputValueCase"
                              ref="saveTagInputCase"
                              size="small"
                              @keyup.enter.native="handleInputConfirmCase('caseLabel')"
                              @blur="handleInputConfirmCase('caseLabel')">
                    </el-input>
                    <el-button v-else
                               class="button-new-tag"
                               size="small"
                               @click="showInputCase">+ 标题分类</el-button>
                  </el-form-item>
                  <el-form-item label="案例中心头部图片:"
                                prop="caseImg">
                    <div class="ele-image-upload-list">
                      <div class="ele-image-upload-item ele-image-upload-button"
                           @click="modalPicTap('dan', 'caseImg', '案例中心头部图片')">
                        <div>
                          <div tabindex="0"
                               class="el-upload el-upload--text">
                            <div class="el-upload-dragger">
                              <i class="el-icon-plus ele-image-upload-icon"></i>
                            </div>

                            <div class="ele-image-upload-item"
                                 style="margin: 0 0 0 0"
                                 v-if="form.caseImg">
                              <div class="el-image">
                                <img :src="form.caseImg"
                                     width="100%"
                                     height="100%"
                                     class="el-image__inner"
                                     style="object-fit: cover" />
                              </div>
                              <div class="ele-image-upload-close"
                                   @click="handleRemove('caseImg')"><i class="el-icon-close"></i></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <el-col :lg="12"
                  :md="12">
            <el-card shadow="never"
                     header="帮助中心配置"
                     body-style="padding: 22px 22px 0 22px;">
              <el-row :gutter="15">
                <el-col :lg="24"
                        :md="24">

                  <el-form-item label="标题分类:"
                                prop="clockTime">
                    <el-tag :key="tag"
                            v-for="tag in dynamicTagsHelp"
                            closable
                            :disable-transitions="false"
                            @close="handleCloseTagHelp(tag,'helpLabel')">
                      {{ tag }}
                    </el-tag>
                    <el-input class="input-new-tag"
                              v-if="inputVisibleHelp"
                              v-model="inputValueHelp"
                              ref="saveTagInputHelp"
                              size="small"
                              @keyup.enter.native="handleInputConfirmHelp('helpLabel')"
                              @blur="handleInputConfirmHelp('helpLabel')">
                    </el-input>
                    <el-button v-else
                               class="button-new-tag"
                               size="small"
                               @click="showInputHelp">+ 标题分类</el-button>
                  </el-form-item>
                  <el-form-item label="帮助中心头部图片:"
                                prop="helpImg">
                    <div class="ele-image-upload-list">
                      <div class="ele-image-upload-item ele-image-upload-button"
                           @click="modalPicTap('dan', 'helpImg', '帮助中心头部图片')">
                        <div>
                          <div tabindex="0"
                               class="el-upload el-upload--text">
                            <div class="el-upload-dragger">
                              <i class="el-icon-plus ele-image-upload-icon"></i>
                            </div>

                            <div class="ele-image-upload-item"
                                 style="margin: 0 0 0 0"
                                 v-if="form.helpImg">
                              <div class="el-image">
                                <img :src="form.helpImg"
                                     width="100%"
                                     height="100%"
                                     class="el-image__inner"
                                     style="object-fit: cover" />
                              </div>
                              <div class="ele-image-upload-close"
                                   @click="handleRemove('helpImg')"><i class="el-icon-close"></i></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <el-col :lg="12"
                  :md="12">
            <el-card shadow="never"
                     header="基础配置"
                     body-style="padding: 22px 22px 0 22px;">
              <el-row :gutter="15">
                <el-col :lg="24"
                        :md="24">

                  <el-form-item label="法律声明:"
                                prop="clockTime">
                    <tinymce-editor v-model="form.legalStatement"
                                    :init="{ height: 350 }" />
                  </el-form-item>

                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <!--上传图片组件-->
        <uploadPictures ref="upload"
                        :isChoice="isChoice"
                        :visible.sync="modalPic"
                        @getPic="getPic"
                        :gridBtn="gridBtn"
                        :gridPic="gridPic"
                        :title="modalTitle"></uploadPictures>
        <!-- 底部工具栏 -->
        <div class="ele-bottom-tool">
          <div v-if="validMsg"
               class="ele-text-danger">
            <i class="el-icon-circle-close"></i>
            <span>{{ validMsg }}</span>
          </div>
          <div class="ele-bottom-tool-actions">
            <el-button type="primary"
                       :loading="loading"
                       @click="submit">
              保存
            </el-button>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import { saveShelp, getHostSysConfigInfo } from '@/api/system/centerCoverImage'
import axios from 'axios';
import position from './components/position.vue';
import { getToken } from '@/utils/token-util';
// import {
//   platformConfigAdd,
//   platformConfigDetail,
//   platformSettingsModify
// } from '@/api/platformSettings/index';
import {
  userOssSignature,
  mainOssSignature
} from '@/api/creatCenter/material';
import {
  addMerchantinfo,
  updateMerchantinfo,
  getMerchantinfo,
  merchantInformationSaveImg,
  merchantInformationDeleteImg,
  merchantInformationPageImg
} from '@/api/staffManage/merchantInformation/index.js';
import uploadPictures from './components/uploadImg';
// import { save, query } from '@/api/agent/pointAllocation';
const DEFAULT_FORM = {
  // oemId: this.$store.state.user.info.oemId,
  // systemIcon: [],
  // site_name:'',
  // browserIcon:[],
  // site_copyright:'',
  // site_beian:'',
  // site_jingbeian:'',
  // loginBackground: [],
  // loginLeftIcon:[],
  // kf_date:'',
  // serviceQrCode:[],
  // kf_mailbox:'',
  // kf_phone:'',
  // kf_address:'',
};
import EleImageUpload from 'ele-admin/es/ele-image-upload';
import request from '@/utils/request';
export default {
  name: 'FormAdvanced',
  components: { uploadPictures, TinymceEditor },
  data () {
    return {
      pricePerKilometerArr: [],

      // 能力名称——能力选择——复选框
      checkSelList: [],
      modalTitle: '',
      modalPic: false,
      isChoice: '单选',
      inputVisibleHelp: false,
      inputVisibleCase: false,
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      // 表单提交状态
      loading: false,
      // 表单数据
      form: {},
      isUpdata: false,
      // 表单验证规则
      rules: {},
      // 表单验证信息
      validMsg: '',
      checkAll: [],
      checkSelAll: [],
      dynamicTagsCase: [],
      dynamicTagsHelp: [],
      form: {
        //  帮助中心头部图片
        helpImg: '',
        // 案例中心头部图片
        caseImg: '',


        // 帮助中心标签
        helpSortLabel: '',
        // 案例中心标签
        caseSortLabel: '',

        // 法律声明
        legalStatement: ''


      },
      //  案例分类标签
      inputValueCase: '',
      //   帮助分类标签
      inputValueHelp: '',
    };
  },
  mounted () {
    this.querys();
  },
  methods: {
    querys () {
      // 查询回显
      getHostSysConfigInfo()
        .then((res) => {

          const msg = res.data
          console.log(msg);
          if (msg.id) {
            //   是修改
            this.$util.assignObject(this.form, {
              ...msg
            });
            this.form.id = msg.id;
            this.isUpdata = true;
            console.log(msg.helpSortLabel.length)
            if (msg.helpSortLabel.length) {
              if (msg.helpSortLabel.includes(',')) {
                console.log('字符串中包含逗号');
                // 包含的进行slice(',') 分割
                this.dynamicTagsHelp = msg.helpSortLabel.split(',').map((item) => item.trim());
              } else {
                console.log('字符串中不包含逗号');
                this.dynamicTagsHelp = msg.helpSortLabel.split();
              }
            }
            if (msg.caseSortLabel.length) {
              if (msg.caseSortLabel.includes(',')) {
                console.log('字符串中包含逗号');
                // 包含的进行slice(',') 分割
                this.dynamicTagsCase = msg.caseSortLabel.split(',').map((item) => item.trim());
              } else {
                console.log('字符串中不包含逗号');
                this.dynamicTagsCase = msg.caseSortLabel.split();
              }

            }


          } else {
            // 修改
            this.isUpdata = false;
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    // 选择图片
    modalPicTap (tit, picTit, openTitle) {
      this.modalTitle = openTitle;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.modalPic = true;
      this.$nextTick(() => {
        this.$refs['upload'].show();
      });
    },
    handleInputConfirmHelp (type) {
      if (type == 'caseLabel') {

        let inputValue = this.inputValueCase;
        if (inputValue) {
          this.dynamicTagsCase.push(inputValue);
        }
        if (this.dynamicTagsCase.length == 1) {
          this.form.caseSortLabel = this.dynamicTagsCase[0];
        } else {
          this.form.caseSortLabel = this.dynamicTagsCase.join(',');
        }

        this.inputVisibleCase = false;
        this.inputValueCase = '';
      } else {

        let inputValue = this.inputValueHelp;
        if (inputValue) {
          this.dynamicTagsHelp.push(inputValue);
        }
        if (this.dynamicTagsHelp.length == 1) {
          this.form.helpSortLabel = this.dynamicTagsHelp[0];
        } else {
          this.form.helpSortLabel = this.dynamicTagsHelp.join(',');
        }

        this.inputVisibleHelp = false;
        this.inputValueHelp = '';
      }
    },
    handleInputConfirmCase (type) {
      if (type == 'caseLabel') {

        let inputValue = this.inputValueCase;
        if (inputValue) {
          this.dynamicTagsCase.push(inputValue);
        }
        if (this.dynamicTagsCase.length == 1) {
          this.form.caseSortLabel = this.dynamicTagsCase[0];
        } else {
          this.form.caseSortLabel = this.dynamicTagsCase.join(',');
        }

        this.inputVisibleCase = false;
        this.inputValueCase = '';
      } else {

        let inputValue = this.inputValueHelp;
        if (inputValue) {
          this.dynamicTagsHelp.push(inputValue);
        }
        if (this.dynamicTagsHelp.length == 1) {
          this.form.helpSortLabel = this.dynamicTagsHelp[0];
        } else {
          this.form.helpSortLabel = this.dynamicTagsHelp.join(',');
        }

        this.inputVisibleHelp = false;
        this.inputValueHelp = '';
      }
    },
    handleCloseTagHelp (tag, type) {
      if (type == 'caseLabel') {
        this.dynamicTagsCase.splice(this.dynamicTagsCase.indexOf(tag), 1);
        if (this.dynamicTagsCase.length == 1) {
          this.form.caseSortLabel = this.dynamicTagsCase[0]
        } else {
          this.form.caseSortLabel = this.dynamicTagsCase.join(',')
        }
      } else {
        this.dynamicTagsHelp.splice(this.dynamicTagsHelp.indexOf(tag), 1);
        if (this.dynamicTagsHelp.length == 1) {
          this.form.helpSortLabel = this.dynamicTagsHelp[0]
        } else {
          this.form.helpSortLabel = this.dynamicTagsHelp.join(',')
        }
      }
    },
    handleCloseTagCase (tag, type) {
      console.log(tag)
      this.dynamicTagsCase.splice(this.dynamicTagsCase.indexOf(tag), 1);
      if (this.dynamicTagsCase.length == 1) {
        this.form.caseSortLabel = this.dynamicTagsCase[0]
      } else {
        this.form.caseSortLabel = this.dynamicTagsCase.join(',')
      }
    },
    pricePerKilometer (value) {
      const result = value.split(',')
      this.pricePerKilometerArr = []
      result.forEach(str => {
        const arr = str.split("-");  // 按照破折号进行分割
        const obj = {
          maximumKilometers: parseInt(arr[0]),  // 将第一个分割结果转换成数值类型并赋值给 minimumKilometers
          minimumKilometers: parseInt(arr[1]),  // 将第二个分割结果转换成数值类型并赋值给 maximumKilometers
          money: parseInt(arr[2])  // 将第三个分割结果转换成数值类型并赋值给 money
        };
        this.pricePerKilometerArr.push(obj)
        this.textList = this.pricePerKilometerArr
      });

      console.log(this.pricePerKilometerArr)
    },
    checkClick (e) {
      console.log('e=====', e);
      this.checkAll = e;
    },
    checkSelClick (e) {
      console.log('e=====', e);
      this.checkSelAll = e;
    },

    // 调用
    selPosition () {
      this.$nextTick(() => {
        // console.log(this.$refs['pos']);
        this.$refs['pos'].show(); // 视频号二维码展示
      });
    },
    // 选中图片
    getPic (pc) {
      console.log('pc========', pc);
      switch (this.picTit) {
        case 'helpImg':
          this.form.helpImg = pc.imgUrl;
          break;

        case 'caseImg':
          this.form.caseImg = pc.imgUrl;
          break;
      }
      this.modalPic = false;
    },
    //删除图片
    handleRemove (field) {
      this.form[field] = '';
    },
    showInputHelp () {
      this.inputVisibleHelp = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInputHelp.$refs.input.focus();
      });
    },
    showInputCase () {
      this.inputVisibleCase = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInputCase.$refs.input.focus();
      });


    },
    /* 表单提交 */
    submit () {
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          // this.pricePerKilometerArr = []
          // if (this.form.travelExpenseType == 3) {
          //   console.log(this.textList)
          //   this.textList.forEach((item) => {
          //     this.pricePerKilometerArr.push(`${item.maximumKilometers}-${item.minimumKilometers}-${item.money}`)
          //   })
          //   this.form.pricePerKilometer = this.pricePerKilometerArr.join(',');

          // }
          // 手机号验证
          if (
            this.form.phone &&
            this.$sun.checkModbile(this.form.phone) == false
          ) {
            this.$message.error('手机号码格式不正确！');
            return;
          }
          // 邮箱验证
          if (
            this.form.email &&
            this.$sun.checkEmail(this.form.email + '.com') == false
          ) {
            this.$message.error('邮箱格式不正确！');
            return;
          }

          this.validMsg = '';
          this.loading = true;

          const data = {
            ...this.form
          };
          console.log(data);

          const saveOrUpdate = this.isUpdata
            ? saveShelp
            : saveShelp;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              // id 不存在则调用查询是否已保存，否则保存多次都会不传id
              // if(!this.form.id){
              this.querys();
              // }
              this.$message.success('提交成功！');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          this.validMsg = ` 共有校验 ${Object.keys(obj).length} 项不通过`;
          return false;
        }
      });
    },

    onUpload (item) {
      console.log('item:', item);
      item.status = 'uploading';
      const formData = new FormData();
      formData.append('file', item.file);
      request({
        url: '/common/uploadFile',
        method: 'post',
        data: formData,
        onUploadProgress: (e) => {
          // 文件上传进度回调
          if (e.lengthComputable) {
            item.progress = (e.loaded / e.total) * 100;
          }
        }
      })
        .then((res) => {
          if (res.data.code === 0) {
            item.status = 'done';
            item.url = res.data.data.url;
            // 如果你上传的不是图片格式, 建议将 url 字段作为缩略图, 再添加其它字段作为最后提交数据
            //item.url = res.data.data.thumbnail;  // 也可以不赋值 url 字段, 默认会显示为一个文件图标
            item.fileUrl = res.data.data.url;
          }
        })
        .catch((e) => {
          item.status = 'exception';
        });
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-button--small {
  margin-left: 10px;
}
.ele-body {
  height: 80vh;
  background-color: #fff;
}
/deep/.ele-bottom-tool-actions {
  text-align: center;
}
.input-new-tag {
  width: 30%;
}
.prompt {
  color: rgb(185, 188, 190);
}
</style>
